package com.dy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dy.entity.Cinema;
import com.dy.entity.Order;
import com.dy.mapper.CinemaMapper;
import com.dy.mapper.OrderMapper;
import com.dy.service.IFeignESServlet;
import com.dy.service.IFeignOrderService;
import com.dy.service.IFeignRedisService;
import com.dy.util.ToolUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Auther: dy
 * @Date: 2022/4/16 - 04 - 16 - 18:57
 * @Description: com.dy.service.impl
 * @version: 1.0
 */
@Service
public class QueueService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CinemaMapper cinemaMapper;
    @Qualifier("com.dy.service.IFeignOrderService")
    @Autowired
    private IFeignOrderService feignOrderService;
    @Qualifier("com.dy.service.IFeignRedisService")
    @Autowired
    private IFeignRedisService feignRedisService;
    @Qualifier("com.dy.service.IFeignESServlet")
    @Autowired
    private IFeignESServlet feignESServlet;

    @RabbitListener(queues = "dyOrderQueue")
    public void getOrder(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG)long tag, Order order) throws IOException {
        //判断冥等性问题
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("order_serial",order.getOrderSerial());
        Order order1 = orderMapper.selectOne(orderWrapper);
        if (order1 == null){
            QueryWrapper<Cinema> wrapper = new QueryWrapper<>();
            wrapper.eq("cinema_name",order.getCinameName());
            Cinema cinema = cinemaMapper.selectOne(wrapper);
            cinema.setCinemaNum(cinema.getCinemaNum()-order.getOrderNumber());
            cinemaMapper.update(cinema,wrapper);
            if (orderMapper.insert(order) > 0 ? true : false){
                feignOrderService.updateOrderState(order.getOrderSerial());
            }
        }
        channel.basicAck(tag,false);
    }

    //消费抢票
    @RabbitListener(queues = "shakedownQueue")
    public void shakedown(Order order) {
        if (ToolUtil.shakedown > 0){
            if (ToolUtil.flag){
                boolean shakedown = feignRedisService.shakedown(order);
                if (shakedown){
                    ToolUtil.shakedown--;
                    ToolUtil.flag = false;
                }
            }else {
                ToolUtil.flag = true;
                //未抢票成功加入es
                feignESServlet.esorder(order);
            }
        }else{
            //未抢票成功加入es

        }
    }
}
